package com.meitianhui.convenitenbuy.module.mine.presenter;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.module.mine.contract.FadeBackContract;
import com.meitianhui.convenitenbuy.module.mine.http.MineApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.model.UserPhotoResponse;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.FadeBackActivity;
import com.meitianhui.convenitenbuy.module.order.model.bean.EmptyInfo;
import com.meitianhui.convenitenbuy.util.PictureUtil;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.BottomMenuDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;


/**
 * Created by amy on 2017/11/17.
 */

public class FadeBackPresenter implements FadeBackContract.Presenter {

    private FadeBackActivity mContext;
    private FadeBackContract.View mView;
    protected static final String IMAGE_FILE_FADE_BACK_PHOTO = "fade_back_photo.png";
    private String imageIds = "";
    private int[] uploadResult = new int[3];

    public FadeBackPresenter(FadeBackActivity activity, FadeBackActivity context) {
        this.mContext = context;
        this.mView = activity;
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

    @Override
    public void openCamera(List<Uri> photoList) {
        Matisse.from(mContext)
                .choose(MimeType.ofAll()) // 选择 mime 的类型
                .countable(true) // 显示选择的数量
                .capture(true)  // 开启相机，和 captureStrategy 一并使用否则报错
                .captureStrategy(new CaptureStrategy(true, "com.meitianhui.convenitenbuy.FileProvider")) // 拍照的图片路径
                .theme(R.style.Matisse_Zhihu) // 黑色背景
                .maxSelectable(5 - photoList.size()) // 图片选择的最多数量
                .gridExpectedSize(mContext.getResources().getDimensionPixelSize(R.dimen.dp_120)) // 列表中显示的图片大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(BottomMenuDialog.CAMER_CODE); // 设置作为标记的请求码，返回图片时使用
    }

    /**
     * 处理图片的回调
     */
    @Override
    public void dealWithPicture(int requestCode, int resultCode, Intent data, List<Uri> photoList) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case BottomMenuDialog.CAMER_CODE://相机
                    List<Uri> urisList = Matisse.obtainResult(data);
                    photoList.addAll(urisList);
                    mView.setAdapterAgain(photoList);
                    break;
                case BottomMenuDialog.LOCAL_CODE:
                    List<Uri> uris = Matisse.obtainResult(data);
                    photoList.addAll(uris);
                    mView.setAdapterAgain(photoList);
                    break;
            }
        }
    }

    @Override
    public void openAlbum(List<Uri> photoList) {
        Matisse.from(mContext)
                .choose(MimeType.ofAll(), false) // 选择 mime 的类型
                .countable(true)
                .maxSelectable(5 - photoList.size()) // 图片选择的最多数量
                .gridExpectedSize(mContext.getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .theme(R.style.Matisse_Zhihu) // 黑色背景
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(BottomMenuDialog.LOCAL_CODE); // 设置作为标记的请求码
    }

    /**
     * 上传用户反馈图片
     */
    @Override
    public void upLoadFadebackPhoto(List<Uri> photoList, String fadeBackNumber, String fadeBackContent) {
        // init upload result.
        uploadResult[0] = photoList.size();   // number of photos
        uploadResult[1] = 0;                  // upload success
        uploadResult[2] = 0;                  // upload failed

        for (Uri uri : photoList) {
            // 可能会因为异常，Bitmap 为 null。考虑如何处理。
            Bitmap bitmap = null;
            try {
                bitmap = PictureUtil.addFilePath(mContext, uri, 400);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            // 将bitmap类型转化成file类型
            File file = new File(Environment.getExternalStorageDirectory().getPath(),
                    IMAGE_FILE_FADE_BACK_PHOTO);
            BufferedOutputStream outputStream = null;
            try {
                outputStream = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.PNG, 10, outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 保存图片至服务器
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
            MultipartBody.Part multpartBody = MultipartBody.Part.createFormData("up_load_file",
                    IMAGE_FILE_FADE_BACK_PHOTO, requestBody);

            MineApiDataSource.getInstance()
                    .uploadHeadImg(InfoProvider.getAppToken(App.getInstance()),
                            "oss_community", "png", "meitianhuiheadImg.png", multpartBody)
                    .subscribe(new ResponseObserver<UserPhotoResponse>(App.getInstance()) {
                        @Override
                        public void onSuccess(UserPhotoResponse response) {
                            HashMap<String, String> data = response.data;
                            String doc_id = data.get("doc_id");
                            if (!TextUtils.isEmpty(doc_id)) imageIds += (doc_id + ",");
                            syncRefreshResult(1);
                        }

                        @Override
                        public void onFail(int code, String msg) {
                            super.onFail(code, msg);
                            syncRefreshResult(2);
                        }
                    });
        }
    }

    /*
     * 同步图片上传的结果，上锁避免多张图片上传时出现修改异常的情况。
     * success : code = 1; failed : code = 2
     */
    private synchronized void syncRefreshResult(int code) {
        if (code == 1) {
            uploadResult[1] = uploadResult[1] + 1;
        } else if (code == 2) {
            uploadResult[2] = uploadResult[2] + 1;
        }

        if ((uploadResult[1] + uploadResult[2]) == uploadResult[0]) {
            if (uploadResult[1] != 0) {
                mView.upLoadImagSuccess();
            } else {
                mView.uploadImgsFailed();
            }
        }
    }

    @Override
    public void upLoadFadebackContent(String fadeBackContent, String fadeBackNumber) {
        // 上传图片成功获取到imageIds,再将content上传服务器
        if (!TextUtils.isEmpty(imageIds)) {
            imageIds = imageIds.substring(0, imageIds.length() - 1);
        }

        // 上传信息
        MineApiDataSource.getInstance()
                .upLoadFadeBack(InfoProvider.getUserToken(mContext).getUser_token(),
                        Constants.CATEGORY_PROPOSE, fadeBackNumber, Constants.CUSTOM_APP,
                        fadeBackContent, imageIds)
                .subscribe(new ResponseObserver<EmptyInfo>(mContext, true) {
                    @Override
                    public void onSuccess(EmptyInfo response) {
                        TipUtils.showToast(mContext, "提交成功我们会采纳你的宝贵意见", 1);
                        mView.upLoadSuccess();
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                    }
                });
    }

}
